package {
	import actors.Crud;
	
	import common.ActorMaster;
	import common.Tank;
	
	import flash.display.Shape;
	import flash.display.Sprite;
	import flash.events.TimerEvent;
	import flash.utils.Timer;
	
	import interfaces.IDestroyable;
	
	import net.hires.debug.Stats;
	
	import spawners.FishSpawner;
	import spawners.GenericSpawner;

	public class FishTank extends Sprite implements IDestroyable {
		private var _actorMaster:ActorMaster;
		private var _tank:Tank;

		private var _appTimer:Timer;
		
		private var _background:Shape;
		private var _fishLayer:Sprite;
		private var _uiLayer:Sprite;
		
		private var _stats:Stats;
		
		private var _destroyed:Boolean;
		
		public function FishTank() {
			_destroyed = false;
		}
		
		public function init():void {
			_tank = Tank.instance;
			
			_tank.width = parent.width;
			_tank.height = parent.height;

			_background = _tank.water;
			_fishLayer = new Sprite();
			_uiLayer = new Sprite();
			addChild(_background);
			addChild(_fishLayer);
			addChild(_uiLayer);

			_actorMaster = ActorMaster.instance;
			_actorMaster.init(_fishLayer);

			
			_appTimer = new Timer(30);
			_appTimer.addEventListener(TimerEvent.TIMER, update);
			_appTimer.start();
			
			//create first wave of fish
//			_actorMaster.addSpawner(new FishSpawner(2000, 1000));
			_actorMaster.addSpawner(new FishSpawner(750, 1000));
			
			//create spawner for crud
			var crudSpawner:GenericSpawner = new GenericSpawner(Crud, 30, -1, _tank.crudGenChance);
			_tank.crudSpawner = crudSpawner;
			_actorMaster.addSpawner(crudSpawner);
			
			toggleStats();
		}
		
		private function update(event:TimerEvent):void {
			if (Math.random() < _tank.crudGenChance) {
				var crud:Crud = new Crud();
				_actorMaster.addActor(crud);
			}
			
			_actorMaster.update();
		}
		
		public function toggleStats():void {
			if (_tank.displayStats) {
				if (_stats)
					_uiLayer.removeChild(_stats);

				_stats = new Stats();
				_uiLayer.addChild(_stats);
			}
			else {
				if (_stats) {
					_uiLayer.removeChild(_stats);
					_stats = null;
				}
			}
		}
		
		public function get destroyed():Boolean {
			return _destroyed;
		}
		
		public function destroy():void {
			if (destroyed)
				return;
			_destroyed = true;
			
			if (_appTimer)
				_appTimer.stop();
				
			_tank.destroy();
			_actorMaster.destroy();
			
			removeChild(_background);
			removeChild(_fishLayer);
			if (_stats)
				_uiLayer.removeChild(_stats);
			removeChild(_uiLayer);
		}
	}
}
